package linkedListAdd;

import java.math.BigInteger;

/**
 * Created by zhaojiuyang1 on 2017/8/24.
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        StringBuffer sb1 = new StringBuffer();
        StringBuffer sb2 = new StringBuffer();
        list2string(l1,sb1);
        list2string(l2,sb2);
        String ls1 = revolveString(sb1.toString());
        String ls2 = revolveString(sb2.toString());
        BigInteger lis1 = new BigInteger(ls1);
        BigInteger lis2 = new BigInteger(ls2);
        BigInteger ri = lis1.add(lis2);
        String ris = ri.toString();
        int last = Integer.valueOf(String.copyValueOf(new char[]{ris.charAt(ris.length()-1)}));
        ListNode listNode = new ListNode(last);
        string2list(listNode,ris,ris.length()-2);
        return listNode;
    }

    private void list2string(ListNode ln,StringBuffer lns){
        lns.append(ln.val);
        if(!hasNext(ln)){
            return ;
        }
        list2string(ln.next,lns);
    }
    private void string2list(ListNode ln,String lns,int index){
        if(-1 == index){
            return;
        }
        int last = Integer.valueOf(String.copyValueOf(new char[]{lns.charAt(index)}));
        ListNode listNode = new ListNode(last);
        ln.next = listNode;
        string2list(listNode,lns,--index);
    }
    private String  revolveString(String str){
        char[] chars = str.toCharArray();
        char[] charr = new char[chars.length];
        for(int i=0;i<chars.length;i++){
            charr[chars.length - (i + 1)] = chars[i];
        }
        return String.copyValueOf(charr);
    }

    private boolean hasNext(ListNode n){
        return n.next != null;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(8);
        l1.next = l2;
        ListNode s1 = new ListNode(0);
        Solution solution = new Solution();
        solution.addTwoNumbers(l1,s1);
    }
}
